package com.hdw.job.batch.reader;

import com.hdw.common.db.DynamicDataSource;
import com.hdw.common.db.HikariDataSourceExt;
import com.hdw.common.util.DateUtil;
import com.hdw.common.util.EtlUtil;
import com.hdw.job.batch.mapper.JDBCWriterRowMapper;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.batch.item.database.builder.JdbcCursorItemReaderBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.Map;

@Configuration
public class CursorReader {


    @Bean(name = "selfJdbcCursorItemReader")
    @StepScope
    public JdbcCursorItemReader<? extends Map> commonCursorReader(JDBCWriterRowMapper jdbcWriterRowMapper
            , @Value("#{jobParameters[querySql]}") String querySql
            , @Value("#{jobParameters[idDbSou]}") String idDbSou
            , @Value("#{jobParameters[dBegin]}") String startDate
            , @Value("#{jobParameters[dEnd]}") String endDate) {
        HikariDataSourceExt souDataSource = DynamicDataSource.getHikariDataSourceById(idDbSou);
        Date start = DateUtil.toDateByFormat(startDate+" 00:00:00", "yyyyMMdd HH:mm:ss");
        Date end = DateUtil.toDateByFormat(endDate+" 00:00:00", "yyyyMMdd HH:mm:ss");
        String qSQL = EtlUtil.buildSql(querySql, start, end, souDataSource.getEuTp());
        try {
            Thread.currentThread().sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new JdbcCursorItemReaderBuilder<Map>()
                .dataSource(souDataSource)
                .name("jdbcCursorItemReader")
                .sql(qSQL)
                .rowMapper(jdbcWriterRowMapper)
                .build();
    }
}
